﻿using UnityEngine;

public class SawCtl : PlatformCtl
{

    private Vector2 leftPoint;
    private Vector2 rightPoint;
    private float targetX;

    public float horizontalSpeed = 1f;

    public override void Start()
    {
        base.Start();

        for (int i=0; i<transform.childCount; i++)
        {
            Transform trans = transform.GetChild(i);
            string nameLower = trans.gameObject.name.ToLower();
            if (nameLower.Contains("left"))
            {
                leftPoint = trans.position;
            }
            else if (nameLower.Contains("right"))
            {
                rightPoint = trans.position;
            }
            Destroy(trans.gameObject);
        }

        targetX = leftPoint.x;
    }


    public override void Update()
    {
        base.Update();
        LeftRightMove();
    }

    private void LeftRightMove()
    {
        if (transform.position.x <= leftPoint.x)
        {
            targetX = rightPoint.x;
        }
        else if (transform.position.x >= rightPoint.x)
        {
            targetX = leftPoint.x;
        }

        transform.position = Vector2.MoveTowards(transform.position, new Vector2(targetX, transform.position.y), horizontalSpeed * Time.deltaTime);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(GameManager.Instance.PlayerTag))
        {
            collision.gameObject.GetComponent<PlayerController>().Death(transform.position.x);
        }
    }
}
